﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using KingRoad.EPM.Web.Areas.SafetyConstruction.ViewModels;
using KingRoad.EPM.SafetyManagementEntity.Model;
using KingRoad.EPM.Web.Areas.SafetyConstruction.SafetyConstructionFramework.Common;
using KingRoad.EPM.SafetyManagementBLL.UIRules;
using Unis.Framework.Core.Infrastructure;
using System.Dynamic;
using System.Data;
using Aspose.Cells;

namespace KingRoad.EPM.Web.Areas.SafetyConstruction.Controllers
{
    public class ScmCostActualController : BaseController
    {
        //
        // GET: /ScmCostActual/
        /// <summary>
        /// 费用使用-列表
        /// </summary>
        /// <returns></returns>
        public ActionResult CostActualList(string pageName)
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            var CostActualmainList = ScmCostactualmainUIRule.GetAllCostactualmainForPage(ViewBag.pageNum, ViewBag.numPerPage, "Cam_OperateTime", out totalRecord, " Cam_Section in (" + Get_JL_JC_ZDJL_SG_SegmentCodes() + ") ");
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            //return View(new ScmCostactualViewModel { TheCostActualMainList = CostActualmainList });
            return String.IsNullOrEmpty(pageName) ? View(new ScmCostactualViewModel { TheCostActualMainList = CostActualmainList }) : View(pageName, new ScmCostactualViewModel { TheCostActualMainList = CostActualmainList });
        }
        /// <summary>
        /// 费用使用-列表(分页提交)
        /// </summary>
        /// <returns></returns>
     
        public ActionResult SplitPage()
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);

            if (ViewBag.pageNum == 0 || ViewBag.numPerPage == 0)
                return CostActualList("CostActualList");

            ViewBag.iput_biaoduan = Request.Form["iput_biaoduan"];
            ViewBag.iput_unit = Request.Form["iput_unit"];
            ViewBag.iput_timestart = Request.Form["iput_timestart"];
            ViewBag.iput_timeend = Request.Form["iput_timeend"];
            string sql = " Cam_Section in (" + Get_JL_JC_ZDJL_SG_SegmentCodes() + ") ";
            if (ViewBag.iput_biaoduan != "")
                sql += " and Cam_Section like '%" + ViewBag.iput_biaoduan + "%' ";
            if (ViewBag.iput_unit != "")
                sql += " and Cam_ConstructionName like '%" + ViewBag.iput_unit + "%' ";
            if (ViewBag.iput_timestart != "")
                sql += " and Cam_YearMonth>='" + Convert.ToDateTime(ViewBag.iput_timestart) + "' ";
            if (ViewBag.iput_timeend != "")
                sql += " and Cam_YearMonth<='" + Convert.ToDateTime(ViewBag.iput_timeend) + "' ";
            var CostActualmainList = ScmCostactualmainUIRule.GetAllCostactualmainForPage(ViewBag.pageNum, ViewBag.numPerPage, "Cam_OperateTime", out totalRecord, sql);
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("CostActualList", new ScmCostactualViewModel { TheCostActualMainList = CostActualmainList });
        }

        /// <summary>
        /// 费用使用-添加
        /// </summary>
        /// <returns></returns>
        public ActionResult CostActualAdd()
        {
            var CostActualList = new List<ScmCostactualInfo> { };
            return View(new ScmCostactualViewModel { TheCostActualList = CostActualList });
        }
        /// <summary>
        /// 费用使用-添加 
        /// 功能：执行添加操作
        /// </summary>
        /// <returns></returns>
        public JsonResult CostActualAddData(ScmCostactualViewModel vm)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                vm.TheScmCostactualmainInfo.Cam_ID = Guid.NewGuid().ToString();
                vm.TheScmCostactualmainInfo.Cam_OperateUserID = GetLoginUserId;              //操作人ID及名称 添加权限时赋值
                vm.TheScmCostactualmainInfo.Cam_OperateUserName = GetLoginUserRealName;
                vm.TheScmCostactualmainInfo.Cam_OperateTime = DateTime.Now;
                vm.TheScmCostactualmainInfo.Cam_State = 0;
                int costactual = ScmCostactualmainUIRule.AddCostactualmain(vm.TheScmCostactualmainInfo);
                if (vm.TheCostActualList != null)
                {
                    foreach (var item in vm.TheCostActualList)
                    {
                        item.Ca_ID = Guid.NewGuid().ToString();
                        item.Cam_ID = vm.TheScmCostactualmainInfo.Cam_ID;
                        int ca = ScmCostactualmainUIRule.AddCostactual(item);
                    }
                }

            });

            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "添加成功",
                    navTabId = "SafetyConstruction.ScmCostActual.CostActualList",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "添加失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 费用使用——编辑
        /// 功能：根据id加载相对应数据
        /// </summary>
        /// <returns></returns>
        public ActionResult CostActualEdit(Guid id)
        {
            var CostActualmainInfo = ScmCostactualmainUIRule.GetCostactualmainById(id);
            var CostActualList = ScmCostactualmainUIRule.GetCostactualByFId(id);
            return View(new ScmCostactualViewModel { TheScmCostactualmainInfo = CostActualmainInfo, TheCostActualList = CostActualList });
            //return View("SafeProductionAdd");
        }
        /// <summary>
        /// 费用使用-修改  
        /// 功能：执行修改保存操作
        /// </summary>
        /// <returns></returns>
        public JsonResult CostActualEditData(ScmCostactualViewModel vm)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                vm.TheScmCostactualmainInfo.Cam_State = 0;
                vm.TheScmCostactualmainInfo.Cam_OperateUserID = GetLoginUserId;              //操作人ID及名称 添加权限时赋值
                vm.TheScmCostactualmainInfo.Cam_OperateUserName = GetLoginUserRealName;
                vm.TheScmCostactualmainInfo.Cam_OperateTime = DateTime.Now;
                int costactual = ScmCostactualmainUIRule.UpdateCostActualmain(vm.TheScmCostactualmainInfo);
                int delcostactual = ScmCostactualmainUIRule.DeleteCostactualByFId(vm.TheScmCostactualmainInfo.Cam_ID);
                foreach (var item in vm.TheCostActualList)
                {
                    item.Ca_ID = Guid.NewGuid().ToString();
                    item.Cam_ID = vm.TheScmCostactualmainInfo.Cam_ID;
                    int cp = ScmCostactualmainUIRule.AddCostactual(item);
                }
            });

            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "更新成功",
                    navTabId = "SafetyConstruction.ScmCostActual.CostActualList",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "更新失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 费用使用引用费用计划列表页
        /// </summary>
        /// <param name="section">标段</param>
        /// <param name="yearmonth">年月</param>
        /// <returns></returns>
        public ActionResult CostActualUnitSel(string section, string yearmonth,string tag)
        {
            ViewBag.tag = tag;
            var TheCostActualList = ScmCostplanmainUIRule.GetCostplanBySql(section, Convert.ToDateTime(yearmonth));
            return PartialView("~/Areas/SafetyConstruction/Views/ScmCostActual/CostActualUnitSel.cshtml", TheCostActualList);
        }
        /// <summary>
        /// 费用使用-查看
        /// </summary>
        /// <returns></returns>
        public ActionResult CostActualView(Guid id)
        {
            var TheScmCostactualmainInfo = ScmCostactualmainUIRule.GetCostactualmainById(id);
            var TheCostActualList = ScmCostactualmainUIRule.GetCostactualByFId(id);
            var TheScmAuditList = ScmAuditUIRule.GetAuditListByPID(id.ToString());
            var TheScmAuditInfo = new ScmAuditInfo();
            if (TheScmAuditList.Count != 0)
            {
                TheScmAuditInfo = TheScmAuditList.FirstOrDefault();
            }
            return View(new ScmCostactualViewModel { TheScmCostactualmainInfo = TheScmCostactualmainInfo, TheCostActualList = TheCostActualList, TheScmAuditInfo = TheScmAuditInfo });
        }
        /// <summary>
        /// 费用使用-审批
        /// </summary>
        /// <returns></returns>
        public ActionResult CostActualAudit(Guid id)
        {
            var CostActualmainInfo = ScmCostactualmainUIRule.GetCostactualmainById(id);
            var CostActualList = ScmCostactualmainUIRule.GetCostactualByFId(id);
            List<SelectListItem> list = new List<SelectListItem>();
            list.Add(new SelectListItem { Text = "审批通过", Value = "true", Selected = true });
            list.Add(new SelectListItem { Text = "审批不通过", Value = "false" });

            ViewBag.auList = list;
            ScmAuditInfo sinfo = new ScmAuditInfo();
            sinfo.A_Time = DateTime.Now;
            sinfo.A_DepID = GetLoginUserDepartmentId;
            sinfo.A_DepName = GetLoginUserDepartmentName;
            sinfo.A_ManID = GetLoginUserId;
            sinfo.A_ManName = GetLoginUserRealName;
            return View(new ScmCostactualViewModel { TheScmCostactualmainInfo = CostActualmainInfo, TheCostActualList = CostActualList, TheScmAuditInfo = sinfo });
        }
        /// <summary>
        /// 费用使用-审批  
        /// 功能：执行审批保存操作
        /// </summary>
        /// <returns></returns>
        public JsonResult CostActualAuditData(ScmCostactualViewModel vm)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                vm.TheScmCostactualmainInfo.Cam_OperateUserID = GetLoginUserId;              //操作人ID及名称 添加权限时赋值
                vm.TheScmCostactualmainInfo.Cam_OperateUserName = GetLoginUserRealName;
                vm.TheScmCostactualmainInfo.Cam_OperateTime = DateTime.Now;
                if (vm.TheScmAuditInfo.A_IsApproved == true)
                {
                    vm.TheScmAuditInfo.A_State = 1;
                    vm.TheScmCostactualmainInfo.Cam_State = 1;
                }
                else
                {
                    vm.TheScmAuditInfo.A_State = 2;
                    vm.TheScmCostactualmainInfo.Cam_State = 2;
                }
                vm.TheScmAuditInfo.A_ID = Guid.NewGuid().ToString();
                vm.TheScmAuditInfo.A_PrimayID = vm.TheScmCostactualmainInfo.Cam_ID;
                ScmAuditUIRule.AddAudit(vm.TheScmAuditInfo, 3, 2);

                var costactualmain = ScmCostactualmainUIRule.UpdateCostActualmain(vm.TheScmCostactualmainInfo);
                int delcostplan = ScmCostactualmainUIRule.DeleteCostactualByFId(vm.TheScmCostactualmainInfo.Cam_ID);
                if (vm.TheCostActualList != null)
                {
                    foreach (var item in vm.TheCostActualList)
                    {
                        item.Ca_ID = Guid.NewGuid().ToString();
                        item.Cam_ID = vm.TheScmCostactualmainInfo.Cam_ID;
                        int ca = ScmCostactualmainUIRule.AddCostactual(item);
                    }
                }
                //更改费用计划状态为3(已经使用)
                var costplanmain = ScmCostplanmainUIRule.UpdateCostPlanmainState(vm.TheScmCostactualmainInfo.Cam_Section, vm.TheScmCostactualmainInfo.Cam_YearMonth);
            });

            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "审批成功",
                    navTabId = "SafetyConstruction.ScmCostActual.CostActualList",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "审批失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        /// <summary>
        /// 费用使用-删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult CostActualDelete(string id)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                int safe = ScmCostactualmainUIRule.DeleteCostactualmain(id);
            });

            dynamic jsonReturn = new ExpandoObject();
            //删除成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "删除成功",
                    navTabId = "SafetyConstruction.ScmCostActual.CostActualList",
                    rel = "",
                    callbackType = "",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "删除失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }
        //
        // GET: /ScmCostLedger/
        /// <summary>
        /// 计量台账-列表
        /// </summary>
        /// <returns></returns>
        public ActionResult CostLedger()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("年份", typeof(string));
            var utlist = GetUnitListByType(1);
            foreach (var item in utlist)
            {
                dt.Columns.Add(item.UNIT_CODE);
            }
            var dtactual = ScmCostactualmainUIRule.GetCostLedger(null, null);
            if (dtactual.Rows.Count > 0)
            {
                //add 前两列
                //清单安全费用（1.5%)
                //提取20%后费用
                DataRow dr1 = dt.NewRow();
                DataRow dr2 = dt.NewRow();
                dr1["年份"] = "清单安全费用（1.5%)";
                dr2["年份"] = "提取20%后费用";

                //end
                int rowcount = dtactual.Rows.Count - 1;
                DateTime min = Convert.ToDateTime(dtactual.Rows[0]["cam_yearmonth"]);
                //      DateTime max = Convert.ToDateTime(dtactual.Rows[rowcount]["cam_yearmonth"]);
                DateTime now = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM") + "-01");
                for (int j = 0; min <= now; j++)
                {
                    var dta = ScmCostactualmainUIRule.GetCostLedger(min, min);
                    DataRow dr = dt.NewRow();
                    DataRow totaldr = dt.NewRow();
                    dt.Columns.Cast<DataColumn>().ToList().ForEach(t =>
                    {
                        var ret = dta.Rows.Cast<DataRow>().ToList().FirstOrDefault(f => f["cam_section"].ToString() == t.ColumnName);
                        var ps = ScmSecurecostUIRule.GetInfoBySql(" Sc_Section = '" + t.ColumnName + "' ");
                        if (ret != null)
                        {
                            dr["年份"] = Convert.ToDateTime(ret["cam_yearmonth"]).ToString("yyyy年M月");
                            dr[t.ColumnName] = ret["amount"];
                        }
                        else
                        {
                            dr["年份"] = min.ToString("yyyy年M月");
                            dr[t.ColumnName] = "";
                        }
                        if (ps != null)
                        {
                            dr1[t.ColumnName] = ps.Sc_Cost;
                            dr2[t.ColumnName] = ps.Sc_Cost * 8 / 10;
                        }

                    });
                    if (j == 0)
                    {
                        dt.Rows.Add(dr1);
                        dt.Rows.Add(dr2);
                    }
                    if (!String.IsNullOrEmpty(dr["年份"].ToString()))
                        dt.Rows.Add(dr);
                    //增加每年的合计
                    if (min.Month == 12 || min == now)
                    {
                        totaldr["年份"] = min.Year + "年合计";

                        var dtatotal = ScmCostactualmainUIRule.GetCostLedger(Convert.ToDateTime(min.Year + "-01-01"), min);
                        dt.Columns.Cast<DataColumn>().ToList().ForEach(t =>
                        {
                            var ret = dtatotal.Rows.Cast<DataRow>().ToList().FindAll(f => f["cam_section"].ToString() == t.ColumnName);
                            if (ret != null)
                            {
                                decimal totalamount = 0;
                                foreach (var item in ret)
                                {
                                    if (item["amount"] == System.DBNull.Value)
                                    {
                                        item["amount"] = 0;
                                    }
                                    totalamount += Convert.ToDecimal(item["amount"]);
                                    totaldr[t.ColumnName] = totalamount.ToString();
                                }

                            }
                        });


                        dt.Rows.Add(totaldr);
                    }

                    min = min.AddMonths(1);
                }
                //增加剩余合计
                DataRow untotaldr = dt.NewRow();
                //增加计量比例
                DataRow ratetotaldr = dt.NewRow();
                untotaldr["年份"] = "剩余合计";
                ratetotaldr["年份"] = "计量比例";

                var dtauntotal = ScmCostactualmainUIRule.GetCostLedger(Convert.ToDateTime(dtactual.Rows[0]["cam_yearmonth"]), now);
                dt.Columns.Cast<DataColumn>().ToList().ForEach(t =>
                {
                    var ret = dtauntotal.Rows.Cast<DataRow>().ToList().FindAll(f => f["cam_section"].ToString() == t.ColumnName);
                    if (ret != null)
                    {
                        //根据列名(标段)查标段金额
                        //此处暂定静态
                        decimal yltj = 0;
                        var ps = ScmSecurecostUIRule.GetInfoBySql(" Sc_Section = '" + t.ColumnName + "' ");

                        decimal untotalamount = 0;
                        decimal totalamount = 0;
                        for (int i = 0; i < ret.Count; i++)
                        {
                            if (ret[i]["amount"] == System.DBNull.Value)
                            {
                                ret[i]["amount"] = 0;
                            }
                            totalamount += Convert.ToDecimal(ret[i]["amount"]);
                            if (i == ret.Count - 1)
                            {
                                yltj = ps.Sc_Cost;
                                untotalamount = yltj * 8 / 10 - totalamount;
                                untotaldr[t.ColumnName] = untotalamount.ToString();

                                ratetotaldr[t.ColumnName] = (totalamount * 100 / (yltj * 8 / 10)).ToString("F2") + "%";
                            }

                        } if (ret.Count==0&&t.ColumnName!="年份")
                        {
                            decimal fee = 0;
                            if (ps!=null)
                            {
                                fee = ps.Sc_Cost;
                            }
                            untotaldr[t.ColumnName] = (fee * 8 / 10).ToString();
                            ratetotaldr[t.ColumnName] = "0.00%";

                        }

                    }
                });
                dt.Rows.Add(untotaldr);
                dt.Rows.Add(ratetotaldr);
            }
            return View(new ScmCostactualViewModel { dt = dt });
        }

        /// <summary>
        /// 费用使用-批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public JsonResult CostActualMultiDelete()
        {
            dynamic jsonReturn = new ExpandoObject();
            var ids = base.GetRequestFormValue<string>("ids");
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                int safe = ScmCostactualmainUIRule.DeleteCostActualmainMulti(ids);
            });

            //保存成功
            if (true)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "删除成功",
                    navTabId = "SafetyConstruction.ScmCostActual.CostActualList",
                    rel = "",
                    callbackType = "",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "删除失败",
                };
            }
            return new JsonResult()
            {
                Data = jsonReturn
            };
        }

        public ActionResult ExportExcelTest(string tableHtml)
        {

            var htmlTable = System.Web.HttpUtility.UrlDecode(tableHtml);

            var loadOptions = new LoadOptions(LoadFormat.Html);
            Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(htmlTable));
            var wb = new Workbook(stream, loadOptions);
            wb.Worksheets[0].AutoFitColumns();
            wb.Worksheets[0].IsGridlinesVisible = true;

            var fileName = "计量台帐.xls";
            string serverPath = Server.MapPath("~/Areas/SafetyConstruction/Upload/Temp/" + fileName);
            wb.Save(serverPath, SaveFormat.Excel97To2003);

            var filePath = "../../Areas/SafetyConstruction/Upload/Temp/" + fileName;
            var result = "{\"src\" : \"" + filePath + "\"}";
            return Content(result);
        }
    }
}
